Skip to main content
Version: Current

Adding a Reference Line

Create a Bar Chart

First let's create a bar chart using layers api.

To create a simple bar chart, we have the following configuration:

HTML

<div id="chart"></div>

JS

const DataModel = await muze.DataModel;

const formattedData = await DataModel.loadData(data, schema);
let rootData = new DataModel(formattedData);

const canvas = muze
.canvas()
.data(rootData)
.rows(["Horsepower"])
.columns(["Year"])
.layers([
{
mark: "bar",
},
]);

The bar chart looks like this:

Add a reference line using layer

Now we add a reference line showing average for all years by adding a tick layer.

Let's create the definition of the tick layer. Specify the mark type and ecodings of the layer as below:

   {
mark: "tick",
encoding: {
x: {
field: null // Here we are plotting a horizontal reference line. Only
// the y value changes, so we set x field as null.
},
y: "Horsepower",
color: {
value: () => "#f71616"
}
}
}

Finally, we create a function which applies aggregation on the data and pass it in source property

{
.transform({
averageLine: function averageLine(dt) {
return dt.groupBy(
[],
[
{
aggn: DataModel.AggregationFunctions.AVG,
field: "Horsepower",
},
],
);
},
})
}

As we had defined defAggFn as avg , so average function will be applied on this aggregation.

Complete code

const DataModel = muze.DataModel;

const formattedData = await DataModel.loadData(data, schema);
let rootData = new DataModel(formattedData);

const canvas = muze
.canvas()
.data(rootData)
.rows(["Horsepower"])
.columns(["Year"])
.transform({
averageLine: function averageLine(dt) {
return dt.groupBy(
[],
[
{
aggn: DataModel.AggregationFunctions.AVG,
field: "Horsepower",
},
],
);
},
})
.layers([
{
mark: "bar",
},
{
mark: "tick",
name: "averageLine",
className: "averageLine",
encoding: {
x: {
field: null,
},
y: "Horsepower",
color: {
value: () => "#f71616",
},
},
calculateDomain: false,
source: "averageLine",
interactive: false,
},
])
.mount("#chart");

The output looks like this:

Adding reference line in crosstab

For adding this reference line in a crosstab, we just need to add a facet dimension to the rows in our previous code.

...
canvas.rows(["Cylinders", "Horsepower"])
...

The output looks like this: